package com.keycloak.admin.services;



import com.keycloak.admin.constants.SMSBusinessCode;
import com.keycloak.admin.model.base.SmsResult;
import com.keycloak.admin.model.params.AliSmsParams;
import com.keycloak.admin.utils.JsonUtils;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.HashMap;
import java.util.Map;
import java.util.Random;

import static com.keycloak.admin.constants.AliSmsTemplateCode.*;

/**
 * YuedaoXingApi
 * com.ydx.api.service
 * Created by Chris Chen
 * 2017/11/8
 * Explain:短信服务
 */
public class SmsService {
    private static final String smsUrl = "http://sh2.cshxsp.com/smsJson.aspx";//业务类短信网关
    private static final String smsSaleUrl = "http://sh.ipyy.com:8888/sms.aspx";  //营销类短信网关
    /**
     * 发送短信验证码
     *
     * @param phone
     * @return 验证码
     * @throws IOException
     */
    public static synchronized AliSmsParams sendVerificationCode(String phone, Integer business,String vcode) throws IOException {
        //String vcode = getVCode();//获取验证码
        Map m=new HashMap();
        String smsContent ="";
        AliSmsParams aliSmsParams = null;
        switch (business) {
            /*case SMSBusinessCode.REG://注册
                smsContent = SmsUtils.getSmsVcodeForReg(vcode);
                m.put("code",vcode);
                ALiSmsService.SendSms(phone,SMS_178466930,m);
                break;
            case SMSBusinessCode.LOGINSMS://验证码登陆
                //smsContent = SmsUtils.getSmsVcodeForLogin(vcode);
                m.put("code",vcode);
                ALiSmsService.SendSms(phone,SMS_178466637,m);
                break;*/
            default:
                smsContent = "您的验证码是: " + vcode;
                m.put("code",vcode);
                aliSmsParams = ALiSmsService.SendSms(phone, SMS_178456859, m);
                break;
        }
        //sendSms(phone, smsContent);
        return aliSmsParams;
    }

    /**
     * 发送短信 HttpURLConnection请求
     *
     * @param phone
     * @param content
     * @return
     * @throws IOException
     */
    public static SmsResult sendSms(String phone, String content) {

        URL url = null;
        HttpURLConnection conn = null;
        try {
            url = new URL(smsUrl);
            conn = (HttpURLConnection) url.openConnection();// 打开连接
            conn.setConnectTimeout(30 * 1000);
            conn.setReadTimeout(30 * 1000);
            // 设置参数
            String params = "action=send&account=jkwl169&password=jkwl16966&mobile=" + phone + "&content=" + content;
            conn.setDoOutput(true);
            OutputStreamWriter out = new OutputStreamWriter(conn
                    .getOutputStream(), "UTF8");
            out.write(params);
            out.flush();
            out.close();
            // 获取返回结果
            BufferedReader reader = new BufferedReader(new InputStreamReader(
                    conn.getInputStream(), "UTF8"));
            StringBuffer sb = new StringBuffer();
            String line = null;
            while ((line = reader.readLine()) != null) {
                sb.append(line + "\r\n");
            }
            reader.close();
            String resultStr = sb.toString();
            //System.out.println("短信服务返回结果---"+resultStr);
            System.out.println("短信服务返回结果---"+resultStr);
            return JsonUtils.fromJson(resultStr, SmsResult.class);
        } catch (MalformedURLException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            conn.disconnect();
        }

        return null;
    }

    //营销类短信发送
    public static SmsResult sendSaleSms(String phone, String content) {
        URL url = null;
        HttpURLConnection conn = null;
        try {
            url = new URL(smsSaleUrl);
            conn = (HttpURLConnection) url.openConnection();// 打开连接
            conn.setConnectTimeout(30 * 1000);
            conn.setReadTimeout(30 * 1000);
            // 设置参数
            String params = "action=send&userid=3401&account=hy10102&password=hy10102&mobile=" + phone + "&content=" + content;
            conn.setDoOutput(true);
            OutputStreamWriter out = new OutputStreamWriter(conn
                    .getOutputStream(), "UTF8");
            out.write(params);
            out.flush();
            out.close();
            // 获取返回结果
            BufferedReader reader = new BufferedReader(new InputStreamReader(
                    conn.getInputStream(), "UTF8"));
            StringBuffer sb = new StringBuffer();
            String line = null;
            while ((line = reader.readLine()) != null) {
                sb.append(line + "\r\n");
            }
            reader.close();
            String resultStr = sb.toString();
           // System.out.println("短信服务返回结果---"+resultStr);
           // MsgUtils.println("短信服务返回结果---"+resultStr);

           /* Map<String, String> ret = new HashMap<>();
            try {
                ret = WXPayUtil.xmlToMap(resultStr);
                JSONObject json = JSONObject.fromObject(ret);
                Gson gson = new Gson();
                SmsResult smsResult = gson.fromJson(json.toString(), SmsResult.class);
                System.out.println("短信服务返回结果---"+smsResult);
                return smsResult;

            } catch (Exception e) {
                e.printStackTrace();
            }
*/



        } catch (MalformedURLException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            conn.disconnect();
        }

        return null;
    }



    /**
     * 获取验证码
     *
     * @return
     */
    public static String getVCode() {
        return String.format("%06d", new Random().nextInt(1000000));
    }
}
